<template>
  <el-aside class="searchBar">
    <div>
      <el-button type="primary" @click="toggleSearch" class="toggle-button">
        {{ showSearch ? '搜索航班' : '模糊搜索' }}
      </el-button>
      <div v-if="showSearch">
        <!-- Start Position Select -->
        <el-select
            class="startPositionSelect"
            v-model="startPosition"
            filterable
            placeholder="出发地"
            style="width: 200px"
            @change="handleStartPositionChange"
        >
          <el-option
              v-for="item in startOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
          />
        </el-select>

        <!-- Aim Position Select -->
        <el-select
            class="aimPositionSelect"
            v-model="aimPosition"
            filterable
            placeholder="目的地"
            style="width: 200px"
            @change="emitFilterEvent"
        >
          <el-option
              v-for="item in aimOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
          />
        </el-select>

        <!-- Date Picker -->
        <div class="block">
          <el-date-picker
              class="date_pick"
              style="width: 100%;height: 100%"
              v-model="selectedDate"
              type="date"
              placeholder="选择日期"
              @change="handleDateChange"
          />
        </div>
      </div>

      <!-- New search box -->
      <div v-else class="airlineIdSearch">
        <el-input placeholder="请输入航班号" v-model="searchFlightId" />
        <svg @click="searchLine" width="30" height="30" viewBox="0 0 48 48" fill="none" xmlns="http://www.w3.org/2000/svg"><path d="M21 38C30.3888 38 38 30.3888 38 21C38 11.6112 30.3888 4 21 4C11.6112 4 4 11.6112 4 21C4 30.3888 11.6112 38 21 38Z" fill="none" stroke="#ffffff" stroke-width="4" stroke-linejoin="miter"/><path d="M26.657 14.3431C25.2093 12.8954 23.2093 12 21.0001 12C18.791 12 16.791 12.8954 15.3433 14.3431" stroke="#ffffff" stroke-width="4" stroke-linecap="butt" stroke-linejoin="miter"/><path d="M33.2216 33.2217L41.7069 41.707" stroke="#ffffff" stroke-width="4" stroke-linecap="butt" stroke-linejoin="miter"/></svg>
      </div>
    </div>
    <p style="height: 5px"></p>
    <div class="result">
      <el-scrollbar height="750px">
        <p class="title">从{{ startPosition }}出发的航班</p>

        <div v-for="item in flightData.data" :key="item.uid" class="scrollbar-demo-item" @click="toDetails(item)">
          <div class="flex items-center space-x-4">
            <svg width="35" height="35" viewBox="0 0 48 48" fill="none" xmlns="http://www.w3.org/2000/svg"><g clip-path="url(#icon-1a3702c92fb27154)"><path d="M4.99707 40.9883L42.9971 40.9883" stroke="#ffffff" stroke-width="4" stroke-linecap="round" stroke-linejoin="miter"/><path d="M8.52068 31.2641L3.90765 23.2741C4.87794 22.7139 9.67924 24.3889 11.4666 25.3061L21.1686 21.8332L12.8733 7.46538L16.9879 7.21842L30.3885 19.6798L38.6389 17.0682C42.2926 16.023 43.4449 18.0188 43.675 18.4175C45.0577 20.8123 42.2639 22.4252 41.8648 22.6556C38.672 24.499 8.52068 31.2641 8.52068 31.2641Z" fill="#9b9b9b" stroke="#ffffff" stroke-width="4" stroke-linecap="round" stroke-linejoin="miter"/></g><defs><clipPath id="icon-1a3702c92fb27154"><rect width="48" height="48" fill="#ffffff"/></clipPath></defs></svg>
            <div>
              <div class="airline text-lg font-semibold">{{ item.airline }}</div>
              <div class="details text-muted-foreground">
                <span> {{ item.duration }} · {{ item.route }} · {{item.startDate}} · {{item.airlineNum}}</span>
              </div>
            </div>
          </div>
          <div class="flex items-center space-x-4">
            <span class="price text-primary font-bold">￥{{ item.price }}</span>
          </div>

        </div>
      </el-scrollbar>
    </div>
  </el-aside>
</template>



<script>
import axios from 'axios';
import dayjs from 'dayjs';

export default {
  data() {
    return {
      showSearch: true, // Toggle state
      flightData: { data: [] },
      startPosition: '',
      aimPosition: '',
      selectedDate: '',
      startOptions: [],
      aimOptions: [],
      searchFlightId:'',
    };
  },

  async mounted() {
    await this.loadStartOptions();
  },
  methods: {
    toggleSearch() {
      this.showSearch = !this.showSearch;
    },
    toDetails(item) {
      const itemQuery = JSON.stringify(item);
      const url = `/details?item=${encodeURIComponent(itemQuery)}`;
      window.open(url, '_blank');
    },

    async loadStartOptions() {
      const token = window.localStorage.getItem("token");
      console.log(token);

      if (!token) {
        console.error('Token not found in sessionStorage.');
        return;
      }

      try {
        const response = await axios.get('http://localhost:8000/flights/geoCoordMap', {
          headers: {
            'Authorization': `Bearer ${token}` // 将 token 作为 Bearer token 发送
          }
        });

        console.log(response.data);

        this.startOptions = Object.keys(response.data).map(key => ({
          value: key,
          label: key
        }));
      } catch (error) {
        console.error('There was an error!', error);
      }
    },

    async handleStartPositionChange() {
      await this.loadAimOptions();
      await this.emitFilterEvent();
    },
    async handleDateChange() {
      await this.loadAimOptions();
      if (!this.aimOptions.some(option => option.value === this.aimPosition)) {
        this.aimPosition = ''; // 如果没有符合条件的航班，清空目的地选择框
      }
      await this.emitFilterEvent();
    },
    async loadAimOptions() {
      try {
        const response = await axios.get('http://localhost:8000/flights/routes');
        const uniqueRoutes = new Set();

        this.aimOptions = response.data.routes
            .filter(route => {
              const routeDate = dayjs(route[0].time).format('YYYY-MM-DD');
              const selectedDate = dayjs(this.selectedDate).format('YYYY-MM-DD');
              return route[0].name === this.startPosition &&
                  (!this.selectedDate || routeDate === selectedDate);
            })
            .map(route => {
              if (!uniqueRoutes.has(route[1].name)) {
                uniqueRoutes.add(route[1].name);
                return {
                  value: route[1].name,
                  label: route[1].name
                };
              }
              return null;
            })
            .filter(route => route !== null);
      } catch (error) {
        console.error('加载目的地数据失败:', error);
      }
    },

    async emitFilterEvent() {
      const filterEvent = new CustomEvent('filter-change', {
        detail: {
          startPosition: this.startPosition,
          aimPosition: this.aimPosition,
          selectedDate: this.selectedDate
        }
      });

      window.dispatchEvent(filterEvent);
      console.log(this.startPosition,this.aimPosition, this.selectedDate)
      console.log("发送form表单申请")
      const response = await axios.post('http://localhost:8000/flights/map/form',
          {startPosition:this.startPosition,
            aimPosition:this.aimPosition,
            Date:this.selectedDate},
          {headers: {
              'Content-Type': 'application/json'
            }});
      if (response.status === 200){
        //console.log(response);
        this.flightData = response.data;
        console.log("flightData信息"+JSON.stringify(this.flightData));
      }
    },
    async searchLine(){
      const response = await  axios.post('http://localhost:8000/flights/searchAirLine',
          {searchFlightId:this.searchFlightId},
          {headers: {
          'Content-Type': 'application/json'
        }});
      if (response.status === 200){
        this.flightData = response.data;
        console.log("flightData信息"+JSON.stringify(this.flightData));
      }
    },
  },
};
</script>

<style scoped lang="less">
.airline {
  font-weight: bold;
  font-size: 16px;
  color: #dbe2ef;
  margin-bottom: 5px;
}

.details {
  font-size: 14px;
  color: #dbe2ef;
}

.price {
  font-size: 24px;
  color: #369f2f; /* 价格颜色 */
  font-weight: bold;
}

.route {
  font-size: 14px;
  color: #dbe2ef;
}

.date_pick {
  background: #2b4b6b;
}

.block {
  padding: 20px 0;
  text-align: left;
  padding-left: 10px;
  border-right: solid 0 px var(--el-border-color);
  width: 430px;
  height: 40px;
  flex: 1;
}

.el-scrollbar {
  margin-bottom: 5px;
}

.searchBar {
  background-color: #2D333E;
  height: 100%;
  width: 450px;
  justify-content: center;
}

.title {
  justify-content: center;
  text-align: center;
  font-size: 28px;
  color: #dbe2ef;
  font-weight: bolder;
}

.startPositionSelect {
  padding-left: 10px;
  margin-top: 10px;
}

.aimPositionSelect {
  margin-left: 28px;
  padding-right: 10px;
  margin-top: 10px;
}

.scrollbar-demo-item {
  border-bottom: 1px solid #dbe2ef;
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px;
  margin: 10px 0;
  background: #2D333E;
  color: #dbe2ef;
  cursor: pointer;
}

.scrollbar-demo-item:hover {
  background:#2D333E;
}

.item-left {
  display: flex;
  align-items: center;
}

.airline-logo {
  width: 24px;
  height: 24px;
  margin-right: 10px;
}

.item-info {
  display: flex;
  flex-direction: column;
}

.item-right {
  display: flex;
  flex-direction: column;
  align-items: flex-end;
}

.toggle-button {
  background-color: #2D333E;
  border-color: #dbe2ef;
  margin-top:10px;
  margin-left: 10px;
  margin-bottom: 10px; /* Add spacing between the button and search components */
}

.traditional-search {
  display: flex;
  flex-wrap: wrap;
}

.airlineIdSearch{
  margin-top: 10px;
  margin-left: 10px;
  margin-right: 30px;
  display: flex;
}
.searchBtn{
  display: flex;
  padding-left: 20px;
  background-color: #2D333E;
}
</style>
